<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use DB;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class CateController extends Controller
{
    //分类添加处理
    public function getAdd()
    {
    	//查询所有分类
    	//$cates=DB::table('cate')->get();
    	$cates = self::getCates();
    	// dd($cates);
    	//解析模板
    	return  view('admin.cate.add',['cates'=>$cates]);
    }

    //根据要求 格式化分类列表  static静态
    public static function getCates()
	{
		$res = DB::table('cate')
		->select(DB::raw("*,concat(path,'-',id) as paths"))
		->orderBy('paths')
		->get();
		// dd($res);

		//处理数据
		foreach($res as $k=>$v){
			$arr = explode('-',$v->path);
			$num = count($arr)-1;
			$res[$k]->title = str_repeat('||---->',$num).$v->title;
		}

		return $res;
	}	

    //处理分类的添加
    public function postInsert(Request $request)
    {
    	// dd($request->all());
    	//处理数据
    	$pid=$request->input('pid');
    	$data=$request->only(['pid','title']);
    	//处理path字段
    	if($pid==0){
    		//添加顶级分类
    		$data['path']='0';
    	}else{
    		//添加子分类
    		//查询父级id找psth路径
    		$res=DB::table('cate')
    		->where('id',$pid)
    		->first();
    		//dd($res);
    		//封装子类的path路径
    		$data['path'] = $res->path.'-'.$pid;
    	}
    	//dd($data);
    	//执行数据的添加
    	$res = DB::table('cate')->insert($data);
   		if($res){
            return redirect('/admin/cate/index')->with('success','分类添加成功');
        }else{
            return back()->with('error','分类添加失败');
        }
    }

    // 分类列表
    public function getIndex(Request $request)
	{
		//$cates = DB::table('cate')->get();
		$cates = DB::table('cate')
		->select(DB::raw("*,concat(path,'-',id) as paths"))
		->orderBy('paths')
		->paginate(5);

		$data = $request->all();
		
		//解析模板
		return view('admin.cate.index',['cates'=>$cates,'data'=>$data]);
	}

	//执行删除
	public function getDelete($id)
	{
		$res = DB::table('cate')->where('pid',$id)->count();
		if($res){
			//证明该分类下有子类 不能删除
			return back()->with('error','该分类下有子类 不能删除');
		}

		$res = DB::table('cate')->where('id',$id)->delete();
		if($res){
			return back()->with('success','分类删除成功');
		}else{
			return back()->with('error','分类删除失败');
		}

	}

	// 修改
	public function getEdit($id)
	{
		//查询
		$catesinfo = DB::table('cate')->where('id',$id)->first();
		// dd($cates);

		$cates = self::getCates();

		//解析模板
		return view('admin.cate.edit',['catesinfo'=>$catesinfo,'cates'=>$cates]);
	}

	//执行修改
	public function postUpdate(Request $request)
	{
		//dd($request->all());
		$id = $request->input('id');
		$data = $request->only(['title','status']);
		$res = DB::table('cate')->where('id',$id)->update($data);
   		if($res){
            return redirect('/admin/cate/index')->with('success','分类修改成功');
        }else{
            return redirect('/admin/cate/index')->with('error','分类修改失败');
        }
	}	
}
